from DrissionPage import ChromiumPage
from lxml import etree
from app.models import TemporaryURL


#用于获取商品详情的url 传入：data→html信息
def GetGoodUrl(data):
    urls = []
    tree = etree.HTML(data)
    prefixes = [
        "//detail.tmall.com/item.htm",
        "//item.taobao.com/item.htm",
    ]

    for prefix in prefixes:
        links = tree.xpath(f"//a[starts-with(@href, '{prefix}')]/@href")
        for link in links:
            link = 'https:'+ link
            #print(link)
            urls.append(link)
    return urls
#用于获取商品详细数据 传入goods_url→单个商品详情页
def GetGoodsMSG(goods_url):
    page_MSG = ChromiumPage()
    page_MSG.get(goods_url)
    data = page_MSG.html
    tree = etree.HTML(data)

    #产品名
    name = tree.xpath('//h1[@class="ItemHeader--mainTitle--3CIjqW5"]/text()')[0]

    #店铺名
    name2 = tree.xpath('//*[@id="root"]/div/div[2]/div[1]/a/div[1]/div[1]/div/text()')[0]

    #价格
    price = tree.xpath('//span[@class="MiniPrice--priceText--M0XSIWl"]/text()')[0]

    #销量
    sales_volume = tree.xpath('//span[@class="ItemHeader--salesDesc--srlk2Hv"]/text()')[0]

    #产地
    addr = tree.xpath('//div[@class="delivery-from-addr"]/text()')[0]

    #宝贝描述 卖家服务 物流服务
    pd = tree.xpath('//div[@class="ShopHeader--scoreText--27uvRGh"]/text()')
    product_description = pd[0]
    seller_services = pd[1]
    logistics_services = pd[2]

    # print(name)
    # print(name2)
    # print(price)
    # print(sales_volume)
    # print(addr)
    # print(product_description,seller_services,logistics_services)
    return name,name2,price,sales_volume,addr,product_description,seller_services,logistics_services
#GetGoodsMSG('https://detail.tmall.com/item.htm?abbucket=12&id=763227943446&ns=1')
#用于搜索商品，并翻页 传入：goods→商品名
def OpenTaobao(goods):
    TemporaryURL.objects.all().delete()
    # d 模式创建页面对象
    page = ChromiumPage()

    #URL
    url = f'https://s.taobao.com/search?initiative_id=staobaoz_20240106&q={goods}'

    #打开搜索页面
    page.get(url)
    data = page.html

    #获取网页详细数据
    for i in range(1):
        urls = GetGoodUrl(data)
        btn = page('下一页', timeout=2)
        if btn:
            btn.click()
            page.wait.load_start()
        # 没有则退出程序
        else:
            break
    for url in urls:
        temporary_url = TemporaryURL(url=url)  # 创建TemporaryURL对象
        temporary_url.save()  # 将对象保存到数据库
